/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.domain.Product;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.Category;
import com.googlecode.bambole.domain.Color;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.ProductFacade;
import com.googlecode.bambole.util.EntryFormatUtil;
import com.googlecode.bambole.util.SearchUtil;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Named("productController")
@SessionScoped
public class ProductController implements Serializable {

    private Product current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.ProductFacade ejbFacade;

    @Inject
    private com.googlecode.bambole.controller.CategoryController categoryController;

    @Inject
    private com.googlecode.bambole.controller.ColorController colorController;

    @Inject
    private com.googlecode.bambole.controller.ImageController imageController;

    private PaginationUtil pagination;
    private Category categorySearch;
    private String priceLastUpdatedSearch;
    private String heightSearch;
    private String lengthSearch;
    private String priceSearch;
    private String weightSearch;
    private String widthSearch;
    private String query;
    private int selectedItemIndex;
    private int recordCount;
    private double currentStoredPrice;
    private boolean searchMode = false;

    public ProductController() {
    }

    public Product getSelected() {
        if (current == null) {
            current = new Product();
        }
        return current;
    }

    public void setSelected(Product current) {
        this.current = current;
    }

    private ProductFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery(), categorySearch);
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery(), categorySearch));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        categorySearch = null;
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery(), categorySearch);

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {
        searchMode = false;
        current = new Product();
        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);
        current.setPriceLastUpdated(date);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        searchMode = false;
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        currentStoredPrice = current.getPrice();

        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();

        current.setUpdated(date);
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        if (current.getPrice() != currentStoredPrice) {
            current.setPriceLastUpdated(date);
        }

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Product getProduct(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        current.setImageNotNull(current.getImage() != null && current.getImage().length > 0);

        if (!EntryFormatUtil.isCodeValid(current.getCode())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("CodeInvalid"));

            retVal = false;
        }

        if (!getFacade().isProductCodeUnique(current.getCode(), current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("CodeAlreadyExists"));

            retVal = false;
        }

        if (current.getPrice() < 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PriceCannotBeNegative"));

            retVal = false;
        }

        if (current.getHeight() < 0 || current.getWeight() < 0 || current.getWidth() < 0 || current.getLength() < 0) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DimensionCannotBeNegative"));

            retVal = false;
        }

        if (!current.isImageNotNull()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("MainImageNotSet"));
        }

        if (current.getColorList() == null || current.getColorList().isEmpty()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("ColorsNotSet"));
        }

        if (current.getImageList() == null || current.getImageList().isEmpty()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("AdditionalImagesNotSet"));
        }

        if (!current.getCategory().isEnabled()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DisabledCategorySelected"));
        }

        if (disabledColorSelected()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DisabledColorSelected"));
        }

        if (current.getTags() != null && !current.getTags().isEmpty() && current.getTags().contains(" ") && !current.getTags().contains(",")) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("CheckTags"));
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT p FROM Product p";
    }

    public String prepareSearch() {
        searchMode = true;

        query = getDefaultQuery();

        priceSearch = null;
        priceLastUpdatedSearch = null;
        weightSearch = null;
        heightSearch = null;
        widthSearch = null;
        lengthSearch = null;

        current = new Product();
        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        searchMode = false;

        boolean queryAddAnd = false;

        boolean queryContainsErrors = false;

        query = getDefaultQuery();

        if ((current.getCode() != null && !current.getCode().isEmpty())
                || (current.getName() != null && !current.getName().isEmpty())
                || (current.getDescription() != null && !current.getDescription().isEmpty())
                || (getPriceSearch() != null && !getPriceSearch().isEmpty())
                || (getPriceLastUpdatedSearch() != null && !getPriceLastUpdatedSearch().isEmpty())
                || (getWeightSearch() != null && !getWeightSearch().isEmpty())
                || (getHeightSearch() != null && !getHeightSearch().isEmpty())
                || (getWidthSearch() != null && !getWidthSearch().isEmpty())
                || (getLengthSearch() != null && !getLengthSearch().isEmpty())
                || (current.getTags() != null && !current.getTags().isEmpty())
                || (current.getCategory() != null)) {

            query = query + " WHERE ";

            if (current.getCode() != null && !current.getCode().isEmpty()) {
                queryAddAnd = true;
                query = query + "p.code LIKE \'%" + current.getCode() + "%\'";
            }

            if (current.getName() != null && !current.getName().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "p.name LIKE \'%" + current.getName() + "%\'";
            }

            if (current.getDescription() != null && !current.getDescription().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "p.description LIKE \'%" + current.getDescription() + "%\'";
            }

            if (getPriceSearch() != null && !getPriceSearch().isEmpty()) {
                String priceSearchClause = SearchUtil.getQueryClause("p.price", getPriceSearch(), 'n', queryAddAnd);
                if (!priceSearchClause.equals("*")) {
                    query = query + priceSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getPriceLastUpdatedSearch() != null && !getPriceLastUpdatedSearch().isEmpty()) {
                String priceLastUpdatedSearchClause = SearchUtil.getQueryClause("FUNC(\'DATE\',p.priceLastUpdated)", getPriceLastUpdatedSearch(), 'd', queryAddAnd);
                if (!priceLastUpdatedSearchClause.equals("*")) {
                    query = query + priceLastUpdatedSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getTags() != null && !current.getTags().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "p.tags LIKE \'%" + current.getTags() + "%\'";
            }

            if (getWeightSearch() != null && !getWeightSearch().isEmpty()) {
                String weightSearchClause = SearchUtil.getQueryClause("p.weight", getWeightSearch(), 'n', queryAddAnd);
                if (!weightSearchClause.equals("*")) {
                    query = query + weightSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getHeightSearch() != null && !getHeightSearch().isEmpty()) {
                String heightSearchClause = SearchUtil.getQueryClause("p.height", getHeightSearch(), 'n', queryAddAnd);
                if (!heightSearchClause.equals("*")) {
                    query = query + heightSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getWidthSearch() != null && !getWidthSearch().isEmpty()) {
                String widthSearchClause = SearchUtil.getQueryClause("p.width", getWidthSearch(), 'n', queryAddAnd);
                if (!widthSearchClause.equals("*")) {
                    query = query + widthSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getLengthSearch() != null && !getLengthSearch().isEmpty()) {
                String lengthSearchClause = SearchUtil.getQueryClause("p.length", getLengthSearch(), 'n', queryAddAnd);
                if (!lengthSearchClause.equals("*")) {
                    query = query + lengthSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (current.getCategory() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                }
                query = query + "p.category = :category";
                categorySearch = current.getCategory();
            }

        }

        if (queryContainsErrors) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidSearchCriteria"));

            return prepareSearch();
        } else {
            recreatePagination();
            recreateModel();

            return "list.xhtml?faces-redirect=true";
        }
    }

    public SelectItem[] getItemsAvailableSelectOne(boolean includeDisabledItems) {

        List<Product> productList;

        if (includeDisabledItems) {
            productList = getFacade().findAll();
        } else {
            productList = getFacade().findEnabled();
        }

        SelectItem[] products = new SelectItem[productList.size() + 1];

        products[0] = new SelectItem(null, null);

        int i = 1;
        for (Product product : productList) {
            products[i++] = new SelectItem(product, product.getCodeAndNameWithDisabledFormatting());
        }

        return products;
    }

    public SelectItem[] getColorsAvailableSelectOne(Product product) {

        SelectItem[] colors;

        if (product == null || product.getId() == null) {

            colors = new SelectItem[1];
            colors[0] = new SelectItem(null, null);

        } else {

            List<Color> colorList = product.getColorList();

            for (Color color : colorList) {
                if (!color.isEnabled()) {
                    colorList.remove(color);
                }
            }

            colors = new SelectItem[colorList.size() + 1];

            colors[0] = new SelectItem(null, null);

            int i = 1;
            for (Color color : colorList) {
                colors[i++] = new SelectItem(color, color.getName());
            }

        }

        return colors;
    }

    public StreamedContent getImage() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent();
        } else {
            byte[] image = new byte[0];
            if (current.getImage() != null) {
                image = current.getImage();
            }
            return new DefaultStreamedContent(
                    new ByteArrayInputStream(image),
                    "image");
        }
    }

    public void imageUpload(FileUploadEvent event) throws IOException {
        current.setImage(IOUtils.toByteArray(event.getFile()
                .getInputstream()));
    }

    public void imageDestroy() {
        current.setImage(null);
    }

    public SelectItem[] getSelectCategory() {
        return categoryController.getItemsAvailableSelectOne(searchMode);
    }

    public SelectItem[] getSelectColors() {
        return colorController.getItemsAvailableSelectMany(current.getColorList());
    }

    private boolean disabledColorSelected() {
        List<Color> currentColorList = current.getColorList();
        if (!currentColorList.isEmpty()) {
            for (Color currentColor : currentColorList) {
                if (!currentColor.isEnabled()) {
                    return true;
                }
            }
        }
        return false;
    }

    public String getPriceSearch() {
        return priceSearch;
    }

    public void setPriceSearch(String priceSearch) {
        this.priceSearch = priceSearch;
    }

    public String getPriceLastUpdatedSearch() {
        return priceLastUpdatedSearch;
    }

    public void setPriceLastUpdatedSearch(String priceLastUpdatedSearch) {
        this.priceLastUpdatedSearch = priceLastUpdatedSearch;
    }

    public String getWeightSearch() {
        return weightSearch;
    }

    public void setWeightSearch(String weightSearch) {
        this.weightSearch = weightSearch;
    }

    public String getWidthSearch() {
        return widthSearch;
    }

    public void setWidthSearch(String widthSearch) {
        this.widthSearch = widthSearch;
    }

    public String getLengthSearch() {
        return lengthSearch;
    }

    public void setLengthSearch(String lengthSearch) {
        this.lengthSearch = lengthSearch;
    }

    public String getHeightSearch() {
        return heightSearch;
    }

    public void setHeightSearch(String heightSearch) {
        this.heightSearch = heightSearch;
    }

    public String prepareImageList() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        imageController.setCurrentProduct(current);

        return "/app/image/list.xhtml?faces-redirect=true";
    }
}
